package com.um.jdy.mp.user.manager;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.platform.code.LoginCode;
import com.um.jdy.common.platform.code.PartnersCode;
import com.um.jdy.common.platform.code.PlatformCode;
import com.um.jdy.common.platform.entity.po.App;
import com.um.jdy.common.platform.entity.po.Merchant;
import com.um.jdy.common.platform.entity.po.MerchantLog;
import com.um.jdy.common.platform.service.AppService;
import com.um.jdy.common.platform.service.MerchantLogService;
import com.um.jdy.common.platform.service.MerchantService;
import com.um.jdy.mp.user.entity.vo.MpAuthVO;
import com.um.jdy.mp.user.entity.vo.MpUserVO;
import com.um.jdy.mp.user.entity.vo.WxAuthLoginVO;
import com.um.jdy.mp.user.service.SessionUserService;
import com.um.springboot.starter.code.CommonCode;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.properties.HshProperties;
import com.um.springboot.starter.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.Date;

/**
 * 管理类：微信
 *
 * @author cs
 * 日期 2023/5/23
 * 版权所有 广州优匠科技有限公司
 */
@Component
@Slf4j
public class WXManager {
    @Autowired
    HshProperties mpProperties;

    @Autowired
    MerchantService merchantService;

    @Autowired
    MerchantLogService merchantLogService;

    @Autowired
    SessionUserService sessionUserService;

    @Autowired
    AppService appService;

    /**
     * 通过js_code获取open_id
     *
     * @param jsCode
     * @return
     */
    public MpAuthVO getOpenId(String jsCode) {

        App app = appService.getEntity("com_id", appService.getComId());

        if(app == null) {
            throw new ServiceException(PlatformCode.PlatformNotExist);
        }

        String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", app.getMpAppId(), app.getMpAppSecrect(), jsCode);
        String response = HttpUtil.get(url);
        log.info("response:{}",response);
        return JSONUtil.from(MpAuthVO.class,response);
    }

    /**
     * 获取微信用户信息
     * @param openid
     * @return
     */
    public MpUserVO getMpUserinfo(String accessToken, String openid) {
        App app = appService.getEntity("com_id", appService.getComId());

        if(app == null) {
            throw new ServiceException(PlatformCode.PlatformNotExist);
        }

        String url = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", accessToken, openid);
        String response = HttpUtil.get(url);
        System.out.print(response);
        return JSONUtil.from(MpUserVO.class,response);
    }

    public WxAuthLoginVO wxAuthLogin(String code) {
        MpAuthVO mpAuthVO = this.getOpenId(code);

        String unionId = "";
        String openId = mpAuthVO.getOpenid();

        if (StrUtil.isBlank(openId)) {
            throw new ServiceException(LoginCode.AuthError);
        }

        MpUserVO mpUser = this.getMpUserinfo(mpAuthVO.getAccess_token(), mpAuthVO.getOpenid());

        System.out.print("mpUser==================> " + mpUser);

        return this.wxAuthLogin(unionId, openId, mpUser.getNickname(), mpUser.getHeadimgurl());
    }


    /**
     * 登陆（openId用户不存在就创建新用户）
     *
     * @param openId
     * @return
     */
    private WxAuthLoginVO wxAuthLogin(String unionId, String openId, String nickname, String headimgurl) {

        Merchant merchant = merchantService.getEntity("mp_open_id", openId);
        WxAuthLoginVO wxAuthLoginVO = new WxAuthLoginVO();

        // 创建新用户
        if (merchant != null) {
            merchant.setMpOpenId(openId);
        } else {
            wxAuthLoginVO.setOpenId(openId);
            wxAuthLoginVO.setNickname(nickname);
            wxAuthLoginVO.setHeadimgurl(headimgurl);
            return wxAuthLoginVO;
        }

        merchantService.save(merchant);

        if (YesOrNo.No.name().equals(merchant.getIsEnable())) {
            throw new ServiceException(CommonCode.AccountDisabled);
        }

        //token
        StpUtil.login(merchant.getPlatformMerchantId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

        MerchantLog loginLog = new MerchantLog();
        loginLog.setPlatformMerchantId(merchant.getPlatformMerchantId());
        loginLog.setCreateTime(new Date());
        loginLog.setComId(merchant.getComId());
        merchantLogService.add(loginLog);

        wxAuthLoginVO.setToken(tokenInfo.getTokenValue());

        return wxAuthLoginVO;
    }

    public Response signin(String code) {
        return Response.success(this.wxAuthLogin(code));
    }

    public void unbind() {
        Merchant user = sessionUserService.getTokenUser();
        if (null == user) {
            throw new ServiceException(PartnersCode.PartnersNotExist);
        }

        if (StrUtil.isBlank(user.getMpOpenId())) {
            throw new ServiceException(LoginCode.AuthError);
        }

        user.setMpOpenId("");
        user.setWxNickName("");
        user.setLogo("");
        //退出登录
        //StpUtil.logout(user.getPlatformMerchantId());
        merchantService.save(user);
    }


}
